//申请管理

var constant = require('../../const');
var models = require('../../models');
var fs = require('fs');
var AV = require('leanengine');
var multiparty = require('multiparty');

function getMemberApplyIndex(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	//0查看申请 1 查看已经申请 2.查看拒绝的
	var status = req.query.status || 0;
	var Authentication = models.MLAuthentication;
	var query = new AV.Query(Authentication);
	query.equalTo("status", 0);
	//	if (status == 0) {
	//		query.equalTo("status", 0)
	//	} else if (status == 1) {
	//		query.equalTo("status", 1)
	//	} else if (status == 2) {
	//		query.equalTo("status", 2)
	//	}
	query.limit(1000);
	query.include("sponsor");
	query.descending("createdAt");
	query.find({
		success: function(results) {
			var data = {
				"username": req.session.username,
				"authentications": results
			};
			res.render('admin/member/authentication', data);
		},
		error: function(error) {
			res.render('admin/member/authentication', {
				"username": req.session.username
			});
		}
	})

}

function handleApply(req, res) {
	var authenticationId = req.body.authenticationId;
	var isAuthentic = req.body.isAuthentic
	var member_type = req.body.member_type || -1;
	var content = req.body.content || "";
	var impress = req.body.impress || "";
	if (isAuthentic == 0) { //认证通过

		var query = new AV.Query(models.MLAuthentication);
		query.include('sponsor');
		// 查找认证记录
		query.get(authenticationId).then(function(auth) {

			auth.set('status', constant.AUTHENTICATION_STATUS_SUCCEED);
			auth.save(null, {
				success: function(results) {
					// 修改申请认证用户的状态
					var sponsor = auth.get('sponsor');
					var sponsorId = sponsor.id;
					sponsor.set('level', parseInt(member_type));
					sponsor.set('impress', impress);
					//免费状态下的认证，将来要删掉
					sponsor.set('isUserInited', 1);
					
					
					sponsor.save(null, {
						success: function(results) {
							//发送通知短信

							AV.Cloud.run('sendSysSms', {
								"tmpName": "通过审核无付费",
								"phone": results.get('mobilePhoneNumber'),
								"name": results.get('nickname')
							}, {
								success: function(result) {
									res.send({
										"code": 0,
										"msg": "发送成功"
									});
								},
								error: function(error) {
									res.send({
										"code": 1,
										"msg": "发送失败"
									});
								}
							});
							res.send({
								"code": 0,
								"msg": "发送成功"
							});
						},
						error: function(error) {
							res.send({
								"code": 1,
								"msg": "请求失败"
							});
						}
					});
				},
				error: function(error) {
					res.send({
						"code": 1,
						"msg": "请求失败"
					});
				}
			});

		});
	} else { //认证未通过
		var query = new AV.Query(models.MLAuthentication);
		query.include('sponsor');
		// 查找认证记录
		query.get(authenticationId).then(function(auth) {
			auth.set('status', constant.AUTHENTICATION_STATUS_FAILED);
			auth.save(null, {
				success: function(results) {
					//发送拒绝短信
					AV.Cloud.run('sendSysSms', {
						"tmpName": "审核未通过",
						"phone": auth.get('sponsor').get('mobilePhoneNumber'),
						"name": auth.get('sponsor').get('nickname'),
						"reason": content
					}, {
						success: function(result) {
							res.send({
								"code": 0,
								"msg": "发送成功"
							});
						},
						error: function(error) {
							res.send({
								"code": 1,
								"msg": "发送失败"
							});
						}
					});
				},
				error: function(error) {
					res.send({
						"code": 1,
						"msg": "请求失败"
					});
				}
			});
		});
	}
}

function contact(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var userId = req.body.userId;
	var content = req.body.content;
	console.log(content)
	AV.Cloud.run('sendSysMsg', {
		"touserId": userId,
		"type": 0,
		"msg": content
	}, null);
	res.send({
		"code": 0,
		"msg": "发送成功"
	});
}

function getSingleMember(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var param = req.query.param || "";
	if (param == "") {
		var mainQuery = new AV.Query(models.MLUser);
		mainQuery.limit(1000);
		mainQuery.equalTo("isUserInited", 1);
	} else {
		var User = models.MLUser;
		var query1 = new AV.Query(User);
		query1.equalTo("molianId", parseInt(param));
		var query2 = new AV.Query(User);
		query2.equalTo("mobilePhoneNumber", param);

		var mainQuery = AV.Query.or(query1, query2);
	}
	mainQuery.include("belongToArticle");
	mainQuery.find({
		success: function(users) {
			console.log(users);
			if (users.length == 0) {
				var data = {
					"username": req.session.username
				};
			} else {
				var data = {
					"username": req.session.username,
					"users": users
				};
			}
			res.render('admin/member/singleMember', data);
		},
		error: function(error) {
			res.render('admin/member/singleMember', {
				"username": req.session.username
			});
		}
	})
}

function getEditIndex(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var id = req.query.id;
	var articlequery = new AV.Query(models.MLArticle);
	articlequery.get(id, {
		success: function(article) {
			var data = {
				"article": article,
				"username": req.session.username
			}
			res.render('admin/memberArticle/write', data);
		},
		error: function(error) {
			//res.success(error);
		}
	})

}

function editMemberArticle(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var form = new multiparty.Form();
	form.parse(req, function(err, fields, files) {
		var articleImg = files.articleImg[0];
		var title = fields.title.toString();
		var articleHtml = fields.articleHtml.toString();
		var articleId = fields.articleId;

		if (articleImg.size !== 0) {
			fs.readFile(articleImg.path, function(err, data) {
				if (err) {
					var data = {
						"username": req.session.username,
						"errMsg": "图片保存失败, 请重试",
					};
					res.render('/admin/member/article/add?userId=' + userId, data);
				}
				var base64Data = data.toString('base64');
				var theFile = new AV.File(articleImg.originalFilename, {
					base64: base64Data
				});
				theFile.save().then(function(theFile) {
					// 文件保存成功, 新增服务
					var article = new models.MLArticle;
					article.set("objectId", articleId);
					article.set("userContent", articleHtml);
					article.set("title", title);
					article.set("title_img", theFile);
					article.set("status", 0);

					article.save({
						success: function() {
							res.send({
								"code": 0,
								"msg": "成功"
							});
						},
						error: function(server, error) {
							console.log(error);
							//res.redirect('/admin/server');
						}
					});
				});
			});
		} else {
			// 文件保存成功, 新增服务
			var article = new models.MLArticle;
			article.set("objectId", articleId);
			article.set("userContent", articleHtml);
			article.set("title", title);

			article.save({
				success: function() {
					res.send({
						"code": 0,
						"msg": "成功"
					});
				},
				error: function(server, error) {
					console.log(error);
				}
			});
		}
	})
}

function getArticleAddIndex(req, res) {
	var userId = req.query.userId;
	console.log(userId)
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	res.render('admin/memberArticle/write', {
		"username": req.session.username,
		"userId": userId
	});
}

function addMemberArticle(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}

	var form = new multiparty.Form();
	form.parse(req, function(err, fields, files) {
		var articleImg = files.articleImg[0];
		var title = fields.title.toString();
		var articleHtml = fields.articleHtml.toString();
		var userId = fields.userId;

		if (articleImg.size !== 0) {
			fs.readFile(articleImg.path, function(err, data) {
				if (err) {
					var data = {
						"username": req.session.username,
						"errMsg": "图片保存失败, 请重试",
					};
					res.render('/admin/member/article/add?userId=' + userId, data);
				}
				var base64Data = data.toString('base64');
				var theFile = new AV.File(articleImg.originalFilename, {
					base64: base64Data
				});
				theFile.save().then(function(theFile) {
					// 文件保存成功, 新增服务
					var article = new models.MLArticle;
					article.set("userContent", articleHtml);
					article.set("title", title);
					article.set("title_img", theFile);
					article.set("status", 0);
					article.set('userId', userId[0]);

					article.save({
						success: function() {
							article.set("address", "http://www.wudutuan.com/member/article?id=" + article.id);
							article.save();
							var User = models.MLUser;
							var user = new User();
							console.log(userId);
							user.set("objectId", userId);
							user.set("belongToArticle", article);
							user.save();
							res.send({
								"code": 0,
								"msg": "成功"
							});
						},
						error: function(server, error) {
							console.log(error);
							//res.redirect('/admin/server');
						}
					});
				});
			});
		} else {
			var data = {
				"username": req.session.username,
				"errMsg": "请选择文件",
			};
			res.render('/admin/member/article/add?userId=' + userId, data);
		}
	})
}

function publishMemberArticle(req, res) {
	if (!req.AV.user) {
		res.redirect('/admin');
	}
	var articleId = req.body.articleId;
	var status = req.body.status;

	var article = new models.MLArticle;
	article.set("objectId", articleId);
	article.set("status", parseInt(status));
	article.set("publishTime", new Date());
	article.save({
		success: function() {
			res.send({
				"code": 0,
				"msg": "成功"
			});
		},
		error: function(server, error) {
			res.send(error);
		}
	});


}

function getMemberArticleIndex(req, res) {
	var id = req.query.id;
	var articlequery = new AV.Query(models.MLArticle);
	articlequery.get(id, {
		success: function(article) {
			var data = {
				"article": article
			}
			res.render('admin/memberArticle/memberArticleView', {
				data: data
			});
		},
		error: function(error) {
			//res.success(error);
		}
	})
}

exports.getMemberApplyIndex = getMemberApplyIndex;
exports.handleApply = handleApply;
exports.contact = contact;
exports.getSingleMember = getSingleMember;
exports.getEditIndex = getEditIndex;
exports.editMemberArticle = editMemberArticle;
exports.getArticleAddIndex = getArticleAddIndex;
exports.addMemberArticle = addMemberArticle;
exports.publishMemberArticle = publishMemberArticle;
exports.getMemberArticleIndex = getMemberArticleIndex;